package 反射;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

//public class Test {
//	public static void main(String[] args) {
//		InvocationHandler handle=new InvocationHandler() {
//			@Override
//			public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
//				if(method.getName().equals("morning")) {
//					System.out.println("Good morning"+args[0]);
//				}
//				return null;
//			}
//		};
//		Hello hello=(Hello)Proxy.newProxyInstance(Hello.class.getClassLoader(), new Class[] {Hello.class}, handle);
//		hello.morning(" Bob");
//	}
//}
//
//interface Hello{
//	void morning(String name);
//}

interface UserBean {
	String getUser();
}

class UserBeanImpl implements UserBean {
	private String user = null;
	// flag:0 ��Ȩ�ޣ�1��Ȩ�ޡ�
	private String flag = null;

	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}

	public UserBeanImpl(String user, String flag) {
		this.user = user;
		this.flag = flag;
	}

	public String getUserName() {
		return user;
	}

	public String getUser() {
		System.out.println("this is getUser() method!");
		return user;
	}

	public void setUser(String user) {
		this.user = user;
		System.out.println("this is setUser() method!");
	}
}

//class UserBeanProxy implements InvocationHandler{
//	private Object targetObject;
//	public UserBeanProxy(Object targetObject) {
//		this.targetObject=targetObject;
//	}
//	@Override
//	public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
//		UserBeanImpl userBean=(UserBeanImpl) targetObject;
//		String flag=userBean.getFlag();
//		Object result=null;
//		if (flag.equals("1")) {
//			result=method.invoke(targetObject, args);
//		}else {
//			System.out.println("sorry , You don't have permission");
//		}
//		return result;
//	}
//}
public class Test {
	public static void main(String[] args) {
		UserBeanImpl targetObject=new UserBeanImpl("aaaa","1");
//		UserBeanProxy proxy=new UserBeanProxy(targetObject);
		InvocationHandler handle=new InvocationHandler() {
			@Override
			public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
				UserBeanImpl userBean=(UserBeanImpl) targetObject;
				String flag=userBean.getFlag();
				Object result=null;
				if (flag.equals("1")) {
					result=method.invoke(targetObject,args);
				}else {
					System.out.println("sorry , You don't have permission");
				}
				return result;
			}
		};
		UserBean object=(UserBean) Proxy.newProxyInstance(targetObject.getClass().getClassLoader(), 
				targetObject.getClass().getInterfaces(), handle);
		String userName=object.getUser();
		System.out.println(userName);
	}
}
